import AbsWindow from "./AbsWindow";

const {ccclass, property} = cc._decorator;
/**
 * 程序常规窗口管理层. 场景中的所有层都在此管理.
 */

@ccclass
export default class WindowManager extends cc.Component {

    // zIndex 永远自增,也即待显示的window 需要修改其zIndex为最顶层.
    private _zIndex: number = 0;

    public findWindow<T extends AbsWindow>(clz: { prototype: T }): T {
        const winName = clz.prototype.winName;
        if (winName) {
            let children = this.node.getComponentsInChildren(clz);
            if (children) {
                for (const comp of children) {
                    if (comp.node.name === winName) {
                        cc.log("找到同类View,", winName);
                        return comp;
                    }
                }
                return null;
            }
        }
        return this.node.getComponentInChildren(clz);
    }

    public addView(win: AbsWindow, index: number) {
        if (!win || !win.node) {
            console.warn("添加null 窗口,将忽略");
            return;
        }
        let widgets = win.getComponent(cc.Widget);
        if (!widgets) {
            widgets = win.addComponent(cc.Widget);
        }
        this.node.addChild(win.node, index || this.incZIndex());

        widgets.left = widgets.top = widgets.right = widgets.bottom = 0;
        widgets.isAlignLeft = widgets.isAlignTop = widgets.isAlignRight = widgets.isAlignBottom = true;
        widgets.updateAlignment();
        win.show();
    }

    public get zIndex(): number {
        return this._zIndex;
    }

    public incZIndex(): number {
        return ++this._zIndex;
    }

    public start() {
    }
}
